package com.itheima.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable() // 禁用 CSRF，适用于 API
                .authorizeRequests()
                .antMatchers("/users/register", "/users/login").permitAll() // 允许所有用户访问注册和登录接口
                .antMatchers("/admin/**").permitAll() // 限制 /admin/** 只能由 ADMIN 角色访问
                .antMatchers("/users/**", "/animals/**", "/review/**").permitAll() // 限制用户、动物和评论相关接口只能由 USER 或 ADMIN 访问
                .anyRequest().authenticated() // 其他所有请求都需要认证
                .and()
                .httpBasic(); // 使用 HTTP Basic 认证
    }
}